<!--
  商户统计图表组件
  @description 商户调用占比饼图和TOP10排行榜
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <div class="merchant-statistics">
    <!-- 饼图 -->
    <div ref="pieChartRef" class="chart-container" v-loading="chartLoading"></div>
    
    <!-- TOP10排行榜 -->
    <div class="ranking-container mt-20px">
      <div class="ranking-title">{{ t('sop.statistics.top10Merchants') }}</div>
      <div class="ranking-list" v-loading="tableLoading">
        <div 
          v-for="(item, index) in rankingData" 
          :key="item.merchantNo"
          class="ranking-item"
        >
          <div class="ranking-number" :class="getRankingClass(index)">
            {{ index + 1 }}
          </div>
          <div class="merchant-info">
            <div class="merchant-name">{{ item.merchantName }}</div>
            <div class="merchant-no">{{ item.merchantNo }}</div>
          </div>
          <div class="merchant-stats">
            <div class="calls-count">
              <span class="label">{{ t('sop.statistics.calls') }}:</span>
              <span class="value">{{ formatNumber(item.totalCalls) }}</span>
            </div>
            <div class="success-rate">
              <span class="label">{{ t('sop.statistics.successRate') }}:</span>
              <span class="value" :style="{ color: getSuccessRateColor(item.successRate) }">
                {{ item.successRate }}%
              </span>
            </div>
          </div>
          <div class="percentage">
            {{ item.percentage }}%
          </div>
        </div>
        
        <!-- 空状态 -->
        <el-empty 
          v-if="!tableLoading && rankingData.length === 0"
          :description="t('sop.statistics.noMerchantData')"
          :image-size="100"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { getMerchantStatisticsApi } from '@/api/sop/statistics'
import type { MerchantStatisticsVO } from '@/api/sop/types'

defineOptions({ name: 'MerchantStatistics' })

const { t } = useI18n()

// Props
const props = defineProps<{
  dateRange: string[]
  loading: boolean
}>()

// Emits
const emit = defineEmits<{
  loadingChange: [loading: boolean]
}>()

// 响应式数据
const chartLoading = ref(false)
const tableLoading = ref(false)
const rankingData = ref<MerchantStatisticsVO[]>([])

// 图表引用
const pieChartRef = ref<HTMLDivElement>()

// 图表实例
let pieChart: ECharts | null = null

// 图表颜色
const colors = [
  '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
  '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#ff9f7f'
]

/**
 * 获取商户统计数据
 */
const getMerchantStatistics = async () => {
  if (!props.dateRange || props.dateRange.length !== 2) return
  
  chartLoading.value = true
  tableLoading.value = true
  emit('loadingChange', true)
  
  try {
    const data = await getMerchantStatisticsApi({
      startTime: props.dateRange[0],
      endTime: props.dateRange[1]
    })
    
    rankingData.value = data
    
    // 更新图表
    await nextTick()
    updateChart()
  } catch (error) {
    console.error('获取商户统计数据失败:', error)
  } finally {
    chartLoading.value = false
    tableLoading.value = false
    emit('loadingChange', false)
  }
}

/**
 * 初始化图表
 */
const initChart = () => {
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value)
  }
}

/**
 * 更新图表
 */
const updateChart = () => {
  if (!pieChart || rankingData.value.length === 0) return
  
  const pieData = rankingData.value.map((item, index) => ({
    name: item.merchantName,
    value: item.totalCalls,
    itemStyle: {
      color: colors[index % colors.length]
    }
  }))
  
  const option = {
    title: {
      text: t('sop.statistics.merchantCallsDistribution'),
      left: 'center',
      top: 20,
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 60,
      bottom: 20,
      data: rankingData.value.map(item => item.merchantName),
      textStyle: { fontSize: 12 }
    },
    series: [{
      name: t('sop.statistics.apiCalls'),
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['35%', '55%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: pieData
    }]
  }
  
  pieChart.setOption(option)
}

/**
 * 调整图表大小
 */
const resizeChart = () => {
  pieChart?.resize()
}

/**
 * 格式化数字
 */
const formatNumber = (num: number) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

/**
 * 获取排名样式类
 */
const getRankingClass = (index: number) => {
  if (index === 0) return 'rank-first'
  if (index === 1) return 'rank-second'
  if (index === 2) return 'rank-third'
  return 'rank-normal'
}

/**
 * 获取成功率颜色
 */
const getSuccessRateColor = (rate: number) => {
  if (rate >= 95) return '#67c23a'
  if (rate >= 90) return '#e6a23c'
  return '#f56c6c'
}

// 监听日期范围变化
watch(() => props.dateRange, () => {
  getMerchantStatistics()
}, { deep: true })

// 组件挂载
onMounted(async () => {
  await nextTick()
  initChart()
  getMerchantStatistics()
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeChart)
})

// 组件卸载
onUnmounted(() => {
  pieChart?.dispose()
  window.removeEventListener('resize', resizeChart)
})
</script>

<style scoped>
.merchant-statistics {
  width: 100%;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.mt-20px {
  margin-top: 20px;
}

.ranking-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.ranking-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 16px;
  text-align: center;
}

.ranking-list {
  max-height: 400px;
  overflow-y: auto;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.ranking-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.ranking-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  margin-right: 12px;
  font-size: 14px;
}

.rank-first {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b8860b;
}

.rank-second {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #696969;
}

.rank-third {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  color: #8b4513;
}

.rank-normal {
  background: linear-gradient(135deg, #909399, #c0c4cc);
}

.merchant-info {
  flex: 1;
  margin-right: 12px;
}

.merchant-name {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.merchant-no {
  font-size: 12px;
  color: #909399;
}

.merchant-stats {
  margin-right: 12px;
}

.calls-count,
.success-rate {
  font-size: 12px;
  margin-bottom: 2px;
}

.label {
  color: #909399;
}

.value {
  font-weight: bold;
  margin-left: 4px;
}

.percentage {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
  min-width: 50px;
  text-align: right;
}
</style>
